package study.nosql.mongodb.dao;

import cn.hutool.core.util.ReflectUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public abstract class BaseDao<E extends BaseDoc> {

    @Autowired
    protected MongoTemplate mongoTemplate;

    /**
     * 新增
     */
    public E insert(E entity) {
        return mongoTemplate.insert(entity);
    }

    /**
     * 删除
     */
    public void delete(String id) {
        E e = ReflectUtil.newInstance(getClazz());
        e.setId(id);
        mongoTemplate.remove(e);
    }

    /**
     * 查询
     */
    public E get(String id) {
        return mongoTemplate.findById(id, getClazz());
    }

    private Class<E> getClazz() {
        //
        Type type = getClass().getGenericSuperclass();
        if (type instanceof Class) {
            throw new RuntimeException("Missing Type Parameter");
        }
        //
        ParameterizedType parameterized = (ParameterizedType) type;
        Class<E> calzz = (Class<E>) parameterized.getActualTypeArguments()[0];
        return calzz;
    }
}
